package com.cdivtc.management.utils;

import com.cdivtc.management.dao.*;
import com.cdivtc.management.pojo.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

@Component


public class ExcelUtils <T> {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private CollageMapper collageMapper;
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MajorMapper majorMapper;
    @Autowired
    private CreateuserMapper createuserMapper;
    static List<String> classname = new ArrayList<>();
    static List<Integer> head_index = new ArrayList<>();
    static List lisst = new ArrayList<>();
    private HSSFWorkbook wb;

    public synchronized Map readExcelByStudent(InputStream stream, Class<T> tClass, String role) throws IOException {

        classname = new ArrayList<>();
        lisst = new ArrayList<>();
        System.out.println("role = " + role);
        Example createuserexample = new Example(Createuser.class);

        Example.Criteria createuserexampleCriteria = createuserexample.createCriteria();
        createuserexampleCriteria.andEqualTo("role", role);
        List<Createuser> select = createuserMapper.selectByExample(createuserexample);
        System.out.println("select = " + select);
        System.out.println("select = " + select.size());
        if (select == null || select.size() == 0) {
            throw new IllegalArgumentException("添加用户失败");

        }
        List<T> STlist = new ArrayList<>();

        List<User> userList = new ArrayList<>();
        List<UserRole> userRoleKeys = new ArrayList<>();

        try {
            //根据路径获取这个操作excel的实例
            for (int i = 0; i < select.size(); i++) {
                lisst.add(select.get(i).getTabletitle());
                classname.add(select.get(i).getClazzname());
            }

            wb = new HSSFWorkbook(stream);
            for (int j = 0; j < wb.getNumberOfSheets(); j++) {
                head_index.clear();
                head_index = new ArrayList<>();
                int finalJ = j;
                //根据页面index 获取sheet页
                HSSFSheet sheet = wb.getSheetAt(finalJ);
// 学生类实体
                HSSFRow row = null;
// 循环sesheet页中数据从第二行开始，第一行是标题
                row = sheet.getRow(1);
                for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
                    String rowstr = row.getCell(i).toString();
                    if (rowstr != null) {
                        int indexof = lisst.indexOf(rowstr.trim());
                        if (indexof != -1)
                            head_index.add(indexof);

                    }
                }
                for (int i = 2; i < sheet.getPhysicalNumberOfRows(); i++) {
// 获取每一行数据
                    row = sheet.getRow(i);

                    User user = new User();
                    T Stu_Tea = tClass.newInstance();

                    System.out.println("classname = " + classname);

                    for (int k = 1; k < row.getPhysicalNumberOfCells(); k++) {
                        Field name = tClass.getDeclaredField(classname.get(head_index.get(k)));
                        name.setAccessible(true);
                        name.set(Stu_Tea, formGetCellType(row.getCell(k)));
                    }

                    //                    设置id
                    Field teachers_students = tClass.getDeclaredField("id");
                    teachers_students.setAccessible(true);
                    String id = String.valueOf(idWorker.nextId());
                    teachers_students.set(Stu_Tea, id);

                    if (role.equals("student")) {
                        teachers_students = tClass.getDeclaredField("studentId");
                        teachers_students.setAccessible(true);

                    } else {
                        teachers_students = tClass.getDeclaredField("jobNumber");
                        teachers_students.setAccessible(true);
                    }
                    String tsnumber = (String) teachers_students.get(Stu_Tea);
//                    设置账号密码
                    user.setUsername(tsnumber);
                    user.setPassword(tsnumber);
//设置状态
                    teachers_students = tClass.getDeclaredField("state");
                    teachers_students.setAccessible(true);
                    teachers_students.set(Stu_Tea, "1");
                    String uid = String.valueOf(idWorker.nextId());
                    System.out.println("uid = " + uid);
                    teachers_students = tClass.getDeclaredField("uId");
                    teachers_students.setAccessible(true);
                    teachers_students.set(Stu_Tea, uid);

                    user.setUid(uid);
                    user.setState("1");

//                    设置学院id
                    Example Collageexample = new Example(Collage.class);
                    Example.Criteria criteria = Collageexample.createCriteria();
                    criteria.andEqualTo("colname", wb.getSheetName(finalJ));
                    Collage collage = collageMapper.selectOneByExample(Collageexample);
//         设置学院
                    teachers_students = tClass.getDeclaredField("college");
                    teachers_students.setAccessible(true);
                    teachers_students.set(Stu_Tea, collage.getColId());

//                    设置班级id

                    if (role.equals("student")) {
//                        获取班级名称 专业名称
                        teachers_students = tClass.getDeclaredField("major");
                        teachers_students.setAccessible(true);
                        String major = (String) teachers_students.get(Stu_Tea);
//查询出专业
                        Major major1 = new Major();
                        major1.setMajorname(major);
                        Major major2 = majorMapper.selectOne(major1);


                        if (major2 != null) {
                            teachers_students = tClass.getDeclaredField("clazzId");
                            teachers_students.setAccessible(true);
                            String clazz = (String) teachers_students.get(Stu_Tea);
                            System.out.println(" = ++++++++++++++++++++++++++++++++++++++");

                            Example clazzexample = new Example(Clazz.class);
                            Example.Criteria clazzcriteria = clazzexample.createCriteria();
                            clazzcriteria.andEqualTo("majorname", major2.getId());
                            clazzcriteria.andEqualTo("clazzName", clazz);

                            Clazz clazzselect = clazzMapper.selectOneByExample(clazzexample);
                            if(clazzselect!=null)
                            teachers_students.set(Stu_Tea, clazzselect.getClazzId() + "");
                        }
                        }


                        UserRole userRoleKey = new UserRole();
                        userRoleKey.setUid(uid);
//查询角色id
                        Role role1 = new Role();
                        role1.setRname(role);
                        Role select1 = roleMapper.selectOne(role1);
                        if (select1 == null)
                            throw new IllegalArgumentException("权限验证错误");
                        userRoleKey.setRid(select1.getRid());
                        userRoleKeys.add(userRoleKey);
                        STlist.add(Stu_Tea);
                        userList.add(user);
                    }
                }

        } catch (Exception e) {

            e.printStackTrace();
            } finally{
            if (wb != null)
                wb.close();
            if (stream != null)
                stream.close();
                Map map = new HashMap();
                map.put("user", userList);
                map.put("student_teacher", STlist);
                map.put("userRoleKeys", userRoleKeys);
                return map;
            }
        }


        public Object formGetCellType (Cell cell){
            Object value = null;
            try {
                if (cell.getCellType() == cell.CELL_TYPE_BLANK) {
                    value = "";
                } else if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
                    value = cell.getBooleanCellValue();
                } else if (cell.getCellType() == cell.CELL_TYPE_ERROR) {
                    value = "";
                } else if (cell.getCellType() == cell.CELL_TYPE_FORMULA) {
                    value = cell.getCellFormula();
                } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
                    if (DateUtil.isCellDateFormatted(cell)) {
                        Date tempValue = cell.getDateCellValue();
                        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                        value = tempValue;
                    } else {
                        Double aDouble = Double.valueOf(cell.getNumericCellValue());
                        value = String.valueOf(aDouble.intValue());
                    }
                } else if (cell.getCellType() == cell.CELL_TYPE_STRING) {
                    value = cell.getStringCellValue();
                } else {
                    value = cell.getDateCellValue();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return value;
        }

}
